<?php

namespace app\admin\model;
use think\Model;
use app\admin\model\AdminLog;
use think\Log;

class Oaapi extends Model
{
    protected $name = "oa_api_log";
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    
    public const url = 'http://oa.fushilai.com.cn:8010/eoffice10/server/public/';
    /**
     * @var string app_key
     */
    public const app_id = '100003';
    
    /**
     * @var string app_secret
     */
    public const app_secret = 'hQEMtBUmgpP6LKY7aWiIbOhoy9m3FNR9';
    
    
    public static function getToken($user_id){
        if(!$user_id){
            exception('获取token,user_id为空');
        }
        $now = time();
        $outTime = $now+3600;
        $api = 'api/open-api/get-token';
        
        $data = [
            "agent_id" => self::app_id,
            "secret" => self::app_secret,
            "user" => $user_id //"admin"
        ];
        
         $token = self::where([
            'api' => 'api/open-api/get-token',
            'outime' => ['GT',$now],
            'user_id' => $user_id
        ])
        ->order('id desc')
        ->value('token');
        
        if(!$token){
            $data = [
                "agent_id" => self::app_id,
                "secret" => self::app_secret,
                "user" => $user_id//"admin"
            ];
            $res = self::curl($api, $data);
            if($res){
                $resArr = json_decode($res,true);
                if($resArr['status'] == 1){
                    self::create([
                        'api' => $api,
                        'user_id' => $user_id,
                        'params' => json_encode($data),
                        'result' => json_encode($res),
                        'token' => $resArr['data']['token'],
                        'refresh_token' => $resArr['data']['refresh_token'],
                        'status' => 1,
                        'outime' => $outTime
                    ]);
                    $token = $resArr['data']['token'];
                }
            }
        } 
        
        if(!$token){
            exception('获取token失败');
        }
        
        return $token;
    }
    
    public static function userList(){
        $data = [
            'api_token' => self::getToken()
        ];
        $res = self::curl('api/user', $data,'GET');
        $arr = json_decode($res,true);
        dump($data);
    }
    
    //创建流程
    public static function flowSave($form_data,$user_id){
        //$form_data = json_encode($form_data);
        //Log::info('提交参数',$form_data);
        
        $data = [
            'api_token' => self::getToken($user_id),
            "flow_id" => "16",
            "flow_run_name" => "终端机-领料申请",
            "run_name_html" => "<div>终端机-领料申请创建流程</div>",
            "form_data" => $form_data
        ];
        
        $res = self::curl('api/flow/new-page/flow-save', $data,'POST','json');
        $resArr = json_decode($res,true);
        
        $run_id = '';
        if($resArr['status'] == 1){
            $run_id = $resArr['data']['run_id'];
            //self::flowUpdate($run_id, $resArr['data']['flow_process'], $form_data['DATA_1']);//没权限
        }
        
        if(!$run_id){
            exception('获取流程id失败');
        }
        
        return $run_id;
    }
    
    //修改流程 api/flow/run/save-flow-run-info
    public static function flowUpdate($run_id,$flow_process,$run_seq){
        //$form_data = json_encode($form_data);
        //Log::info('提交参数',$form_data);
        
        $data = [
            "run_id" => $run_id,
            "flow_process" => $flow_process,
            "run_seq" => $run_seq,
        ];
        
        $res = self::curl('api/flow/run/save-flow-run-info', $data,'POST','json');
    }
    
    //结束流程、提交流程
    public static function flowTurning($run_id,$turn_data,$user_id){
        $data = [
            'api_token' => self::getToken($user_id),
            "run_id" => $run_id,
            "process_id" => '1'
        ];
        $data = array_merge($data,$turn_data);
        
        Log::info($data,'OA-结束流程');
        
        $res = self::curl('api/flow/run/flow-turning', $data,'POST','json');//'POST','json'
        $resArr = json_decode($res,true);
        
        if($resArr['status'] == 1){
            return $resArr['data'];
        }else{
            exception('结束流程失败:'.$resArr['errors'][0]['message']);
        }
    }
    
    /**
     * 接口调用
     * @param string $url
     * @param string $postData
     * @param array $headers
     * @return bool|string
     */
    public static function curl($api,$data,$method = 'POST',$headers = '')
    {
        Log::info($api,'OA-API');
        Log::info($data,'OA-提交参数');
        if (is_array($data)&&!$headers) {
            $data = http_build_query($data);
        }
        
        myLog('OA-API',$api);
        myLog('OA-提交参数',$data);
        
        $ch = curl_init();
        $url = config('site.oa_host');
        curl_setopt($ch, CURLOPT_URL, $url . $api);//self::url
        
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if ($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);
        } else {
            curl_setopt($ch, CURLOPT_POST, 0);
        }
        
        if($headers){
            //设置头部
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
            $data = json_encode($data);
            Log::info($data,'OA-提交参数-json_encode');
        }
        
        if ($data) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        
        /* if (!empty($headers)) {
            curl_setopt_array($ch, $headers);
        } */
        
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        $data = curl_exec($ch);
        
        Log::info(json_decode($data),'OA-返回结果');
        myLog('返回结果',$data);
        
        curl_close($ch);
        return $data;
    }
}
